    package com.yifeng.servlet.admin;
    import com.yifeng.common.Result;
    import com.yifeng.factory.ServiceFactory;
    import com.yifeng.model.Resource;
    import com.yifeng.service.ResourceService;
    import com.yifeng.servlet.BaseServlet;
    import com.yifeng.util.JwtUtil;
    import io.jsonwebtoken.Claims;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
    import java.io.IOException;
    @WebServlet("/admin/resources/*")
    @MultipartConfig(maxFileSize = 1024 * 1024 * 10)//10MB
    public class ResourceServlet extends BaseServlet {
        /*
        负责人：鹿鸣

        功能：资源业务逻辑服务实例，用于处理资源相关的业务操作

        参数：无

        返回值：无
        */
        private final ResourceService resourceService = ServiceFactory.getResourceService();
        /*
        负责人：鹿鸣

        功能：处理HTTP请求的核心方法，根据请求方法和路径分发到不同的处理方法

        参数：req - HTTP请求对象, resp - HTTP响应对象

        返回值：无
        */
        @Override
        protected void doHandle(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            String method = req.getMethod();
            String pathInfo = req.getPathInfo();
            switch (method) {
                case "GET":
                    handleGet(req, resp, pathInfo);
                    break;
                case "POST":
                    handlePost(req, resp);
                    break;
                case "DELETE":
                    handleDelete(req, resp, pathInfo);
                    break;
                default:
                    writeJson(resp, Result.fail(405,"请求方法错误"+ method));
            }
        }

        /*
        负责人：鹿鸣

        功能：处理GET请求，支持分页查询和关键词搜索资源

        参数：req - 请求对象, resp - 响应对象, pathInfo - 路径信息

        返回值：无
        */
        private void handleGet(HttpServletRequest req, HttpServletResponse resp, String pathInfo) throws IOException {
            // 处理 pathInfo 为 null 的情况
            if (pathInfo == null) {
                pathInfo = "/"; // 统一视作根路径
            }
            // 现在 pathInfo 肯定不为 null，可以安全使用
            if (!pathInfo.equals("/") && !pathInfo.isEmpty()) {
                // 检查是否是下载路径：/123/download
                if (pathInfo.matches("^/\\d+/download$")) {
                    String resourceIdStr = pathInfo.substring(1, pathInfo.lastIndexOf("/"));
                    handleDownload(req, resp, resourceIdStr);
                    return;
                }
                // 其他非根路径（如 /123）暂不支持
                writeJson(resp, Result.fail(406,"暂不支持单条资源查询"));
                return;
            }


            // 获取搜索关键词
            String keyword = req.getParameter("keyword");


            if (keyword != null && !keyword.trim().isEmpty()) {
                Result result = resourceService.searchResources(keyword.trim());
                writeJson(resp, result);
            } else {
                Result result = resourceService.getAllResources();
                writeJson(resp, result);

            }
        }

        /*
        负责人：鹿鸣

        功能：处理POST请求，添加新资源

        参数：req - 请求对象, resp - 响应对象

        返回值：无
        */
        private void handlePost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            try {
                // 获取当前用户
                String  currentUser = getCurrentUser(req);
                if (currentUser == null) {
                    writeJson(resp, Result.fail(401,"用户未登录"));
                    return;
                }
                // 处理文件上传
                if (isMultipart(req)) {
                    handleFileUpload(req, resp, currentUser);
                } else {
                    handleJsonRequest(req, resp);
                }
            } catch (Exception e) {
                e.printStackTrace();
                writeJson(resp, Result.fail(406,"请求处理失败"));
            }
        }
        //处理上传

        private void handleFileUpload(HttpServletRequest req, HttpServletResponse resp, String currentUser)
                throws IOException, ServletException {

            Part filePart = req.getPart("file");


            // 参数验证
            if (filePart == null || filePart.getSize() == 0) {
                writeJson(resp, Result.fail(400,"未选择文件"));
                return;
            }

            Result result = resourceService.uploadResource(filePart, currentUser);
            writeJson(resp, result);
        }

        //把资源信息添加数据库
        private void handleJsonRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            Resource resource = readJsonBody(req, Resource.class);
            if (resource == null) {
                writeJson(resp, Result.fail(400,"请求体为空"));
                return;
            }
            Result result = resourceService.addResource(resource);
            writeJson(resp, result);
        }


        //判断multipart请求
        private boolean isMultipart(HttpServletRequest req) {
            String contentType = req.getContentType();
            return contentType != null && contentType.startsWith("multipart/");
        }

        //获取token
        private String  getCurrentUser(HttpServletRequest req) {
         /*简易获取token信息*/
            String authHeader = req.getHeader("Authorization");
            if (authHeader == null) {
                return null;
            }
             Claims claims = JwtUtil.parseToken(authHeader);

            String username = (String) claims.get("username");
            return username;


          /* 前端请求头 headers: {
                'Authorization': 'Bearer ' + jwtToken  // 关键在这里！
            },*/

           // 得到： "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xxxxx"
           /* if (authHeader != null && authHeader.startsWith("Bearer ")) {
                String token = authHeader.substring(7); // 去掉 "Bearer "（7个字符）
                Claims claims = JwtUtil.parseToken(token); // 解析 JWT
            }*/
        }


        //处理下载
        private void handleDownload(HttpServletRequest req, HttpServletResponse resp, String resourceIdStr) throws IOException {



            try {
                int resourceId = Integer.parseInt(resourceIdStr);
                Result result = resourceService.downloadResource(resourceId, resp);
                if (result != null) {
                    // 仅当 result 不为 null 时才写 JSON（说明出错）
                    writeJson(resp, result);
                }
                // 如果 result == null，说明已成功写入文件流，无需再响应
            } catch (NumberFormatException e) {
                writeJson(resp, Result.fail(400,"资源ID格式错误"));
            }
        }




        /*
        负责人：鹿鸣

        功能：处理DELETE请求，删除指定资源

        参数：req - 请求对象, resp - 响应对象, pathInfo - 路径信息

        返回值：无
        */
        private void handleDelete(HttpServletRequest req, HttpServletResponse resp, String pathInfo) throws IOException {

            if (pathInfo != null && pathInfo.length() > 1) {
                String resourceIdStr = pathInfo.substring(1);
                try {
                    int resourceId = Integer.parseInt(resourceIdStr);
                    Result result = resourceService.deleteResourceById(resourceId);
                    writeJson(resp, result);
                } catch (NumberFormatException e) {
                    writeJson(resp, Result.fail(400,"资源ID格式错误"));
                }
            } else {
                writeJson(resp, Result.fail(400,"未指定资源ID"));
            }

        }
    }